package org.helgoboss.bash

import java.io.File
import org.helgoboss.scala_additions.Implicits._

class BashCommand (
            exeFile: File,
            rcFile: Option[File],
            interactive: Boolean,
            startupDir: Option[File]
        ) {
        
    val components = {
        List (
            List(exeFile.osDependentPathExpression),
            actualRcFile match {
                case Some(f) => List("--rcfile", f.cygwinCompatibleUnixPathExpression)
                case None => Nil
            },
            if (interactive) List("-i") else Nil
        ).flatten
    }
    
    lazy val actualRcFile = rcFile match {
        case Some(configuredRcFile) => 
            startupDir match {
                case Some(d) => 
                    Some(generateRcFileWithStartupDir(startupDir = d, configuredRcFile = Some(configuredRcFile)))
                    
                case None => 
                    Some(configuredRcFile)
            }
            
        case None => 
            startupDir match {
                case Some(d) =>
                    Some(generateRcFileWithStartupDir(startupDir = d, configuredRcFile = None))
                    
                case None =>
                    None
            }
    }
    
    private def generateRcFileWithStartupDir(startupDir: File, configuredRcFile: Option[File]) = {
        val f = File.createTempFile("org.helgoboss.bash.rc_", ".sh")
        val part1 = "cd \"" + startupDir.cygwinCompatibleUnixPathExpression + "\""
        val part2 = configuredRcFile match {
            case Some(f) => "\nsource \"" + f.cygwinCompatibleUnixPathExpression + "\""
            case None => ""
        }
        f.content = part1 + part2
        f
    }
}